<template>
  <div class="issue">
    <div class="layout-content">
      <!-- 指定公司 -->
      <DesignateCompany
        ref="designateCompany"
        v-model="designateCompanyForm"
        :updateQuotationDetail="updateQuotationDetail"
        @change="designateCompanyChange"
      />
    </div>
    <div class="layout-content">
      <div class="form-wrapper">
        <c-form
          ref="issueForm"
          :data="formData"
          v-model="form"
          :rules="formRules"
          :col="{
            labelCol: { style: 'width: 100px' }
          }"
        >
          <!-- 商品品种 -->
          <template v-slot:category>
            <span v-if="isUpdating"
              >{{ updateQuotationDetail.categoryName }}
            </span>
            <c-category
              v-else
              v-model="form.category"
              getItem
              @change="changeCategory"
            />
          </template>
          <template v-slot:priceType>
            <span v-if="isUpdating"
              >{{ updateQuotationDetail.priceType === 1 ? "点价" : "确定价" }}
            </span>
            <a-radio-group
              v-model="form.priceType"
              @change="changePriceType"
              v-else
            >
              <a-radio :value="1">
                点价
              </a-radio>
              <a-radio :value="2">
                确定价
              </a-radio>
            </a-radio-group>
          </template>
          <!-- 合约月 -->
          <template v-slot:contract>
            <c-futures
              v-model="form.contract"
              :futuresCode="futuresCode"
            ></c-futures>
          </template>
          <!-- 下单倍数 -->
          <template v-slot:rateLimitType>
            <div>
              <a-radio-group v-model="form.rateLimitType">
                <a-radio :value="0">
                  开启
                </a-radio>
                <a-radio :value="1">
                  关闭
                </a-radio>
              </a-radio-group>
              <a-alert
                class="inline-b"
                type="warning"
                show-icon
                message="开启后，客户下单数量需要满足倍数要求"
              />
            </div>
          </template>
          <!-- 商品信息 -->
          <template v-slot:goodsData>
            <ProductInfo
              v-model="form.goodsData"
              ref="productInfo"
              :priceType="
                isUpdating ? updateQuotationDetail.priceType : form.priceType
              "
              :categoryCode="form.category"
              :originalData="originalData"
              @addRow="goodsDataAdd"
              @delRow="goodsDataDel"
              @addWarehouseSuccess="submit"
            />
          </template>
          <!-- 交货方式 -->
          <template v-slot:deliveryType>
            <SelectCreate
              v-model="form.deliveryType"
              :data="deliveryTypeList"
              placeholder="请选择交货方式"
            />
          </template>
          <!-- 开票日期 -->
          <template v-slot:invoiceType>
            <SelectCreate
              v-model="form.invoiceType"
              :data="invoiceTypeList"
              placeholder="请选择开票日期"
            />
          </template>
          <!-- 结算方式 -->
          <template v-slot:settlementType>
            <SelectCreate
              v-model="form.settlementType"
              :data="settlementTypeList"
              placeholder="请选择结算方式"
            />
          </template>
          <!-- 截止日期 -->
          <template v-slot:cutoffDate>
            <div class="cutoffDate">
              <a-date-picker
                v-model="form.cutoffDate"
                :showToday="false"
                :disabled-date="disabledDate"
                placeholder="请选择日期和时间"
                :allowClear="false"
                format="YYYY-MM-DD HH:mm"
                valueFormat="x"
                :show-time="{
                  defaultValue: moment('15:00', 'HH:mm'),
                  format: 'HH:mm',
                  minuteStep: 15
                }"
              />
            </div>
          </template>
        </c-form>
        <c-button
          type="primary"
          width="200px"
          style="margin-left: 100px;"
          @click="submitVerify"
          :loading="submitLoading"
          >确认发布</c-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import ProductInfo from "./components/productInfo";
import DesignateCompany from "./components/designateCompany";
import SelectCreate from "@/components/select-create";
import {
  releaseQuotation,
  getquotationdetailtoupdate,
  updatequotation,
  verifyhistorypremium,
  getline
} from "@/api/quotation";
import { historyPremiumVerify } from "@/util/mixins/historyPremiumVerify";
import { findIndex } from "lodash";
import getTime from "./getDefaultTime.js";
import quotationDict from "@/dict/quotation";

export default {
  components: {
    DesignateCompany,
    ProductInfo,
    SelectCreate
  },
  mixins: [historyPremiumVerify],
  data() {
    return {
      quotationDict,
      designateCompanyForm: {
        companys: []
      },
      // 是否编辑状态
      isUpdating: false,
      // 编辑报价的详情
      updateQuotationDetail: {},
      // 交货方式初始数据
      deliveryTypeList: [
        {
          title: "转货权"
        },
        {
          title: "卖家送货"
        },
        {
          title: "买家自提"
        }
      ],
      // 开票日期初始数据
      invoiceTypeList: [
        {
          title: "本月开票"
        },
        {
          title: "下月开票"
        }
      ],
      // 结算方式初始数据
      settlementTypeList: [
        {
          title: "转账"
        },
        {
          title: "承兑"
        },
        {
          title: "电汇"
        }
      ],
      formData: [
        {
          label: "商品种类",
          prop: "category",
          slot: "category"
        },
        {
          label: "作价方式",
          prop: "priceType",
          slot: "priceType"
        },
        {
          hidden: false,
          label: "输入价格",
          prop: "slidePriceType",
          type: "radio",
          typeData: [
            {
              label: "基价",
              value: 1
            },
            {
              label: "含税单价（结算价）",
              value: 2
            }
          ]
        },
        {
          hidden: false,
          label: "合约月",
          prop: "contract",
          slot: "contract"
        },
        {
          hidden: false,
          label: "升贴水",
          prop: "premiumIsshow",
          type: "radio",
          typeData: [
            {
              label: "显示",
              value: true
            },
            {
              label: "隐藏",
              value: false
            }
          ]
        },
        {
          label: "商品信息",
          prop: "goodsData",
          slot: "goodsData"
        },
        {
          label: "下单倍数",
          prop: "rateLimitType",
          slot: "rateLimitType"
        },
        {
          hidden: true,
          label: "最低倍数",
          prop: "multiple",
          type: "number",
          min: 1
        },
        {
          label: "交货方式",
          prop: "deliveryType",
          slot: "deliveryType"
        },
        {
          label: "开票日期",
          prop: "invoiceType",
          slot: "invoiceType"
        },
        {
          label: "结算方式",
          prop: "settlementType",
          slot: "settlementType"
        },
        {
          label: "线路设置",
          prop: "lineSwitch",
          type: "radio",
          typeData: [
            {
              label: "开启",
              value: 1
            },
            {
              label: "关闭",
              value: 2
            }
          ]
        },
        {
          hidden: true,
          label: "选择线路",
          prop: "line",
          placeholder: "请选择线路",
          type: "select",
          dropdownMatchSelectWidth: false,
          replaceFields: {
            label: "line",
            value: "id"
          },
          typeData: []
        },
        {
          label: "截止日期",
          prop: "cutoffDate",
          slot: "cutoffDate"
        },
        {
          label: "备注",
          prop: "remark",
          type: "textarea"
        }
      ],
      form: {
        category: [], // 品种
        priceType: 1, // 作价方式
        slidePriceType: 1, // 输入价格 1、基价 2、含税单价结算价
        contract: undefined, // 合约月
        premiumIsshow: true, // 升贴水、价格
        rateLimitType: 1, // 下单倍数开关
        multiple: undefined, // 下单倍数
        goodsData: [
          // 商品信息
          {
            brand: undefined, // 品牌
            spec: undefined, // 规格
            material: undefined, // 材质
            other: undefined, // 其他
            amount: undefined, // 数量
            warehouseName: undefined, // 仓库
            price: undefined, // 价格
            premium: undefined // 升贴水
          }
        ],
        lineSwitch: 2, // 线路开关
        line: undefined, // 线路
        settlementType: "转账", // 结算方式
        deliveryType: "转货权", // 交货方式
        invoiceType: "本月开票", // 开票日期
        // delaySwitch: 2, // 延期开关
        cutoffDate: undefined, // 截止日期
        remark: undefined // 备注
      },
      // 校验规则
      formRules: {
        category: [
          { required: true, message: "请选择商品种类", trigger: "change" }
        ],
        contract: [
          { required: true, message: "请选择合约月", trigger: "change" }
        ],
        multiple: [
          { required: true, message: "请输入最低倍数", trigger: "change" }
        ],
        deliveryType: [
          { required: true, message: "请选择交货方式", trigger: "change" }
        ],
        invoiceType: [
          { required: true, message: "请选择开票日期", trigger: "change" }
        ],
        settlementType: [
          { required: true, message: "请选择结算方式", trigger: "change" }
        ],
        line: [{ required: true, message: "请选择线路", trigger: "change" }]
      },
      originalData: [], // 商品信息原始数据
      futuresCode: undefined, // 品种code，用于查询对应的合约月
      submitLoading: false
    };
  },
  watch: {
    // 监听作价方式
    "form.priceType": {
      handler: function() {
        let props = this.formData.map(i => i.prop);
        let data = ["slidePriceType", "contract", "premiumIsshow"];
        data.forEach(item => {
          let idx = props.indexOf(item);
          this.formData[idx].hidden = this.form.priceType === 1 ? false : true;
        });
      }
    },
    // 监听下单倍数开关
    "form.rateLimitType": {
      handler: function() {
        let props = this.formData.map(i => i.prop);
        let idx = props.indexOf("multiple");
        this.formData[idx].hidden =
          this.form.rateLimitType === 0 ? false : true;
        if (this.form.rateLimitType === 1) this.form.multiple = undefined;
      }
    },
    // 监听线路开关
    "form.lineSwitch": {
      handler: function() {
        let props = this.formData.map(i => i.prop);
        let idx = props.indexOf("line");
        this.formData[idx].hidden = this.form.lineSwitch === 1 ? false : true;
        if (this.form.lineSwitch === 1) {
          this.getOrderLines().then(res => {
            this.formData[idx].typeData = res;
          });
        }
      }
    }
  },
  methods: {
    moment,
    // 切换作价方式
    changePriceType() {
      this.form.goodsData = [
        // 商品信息
        {
          brand: undefined, // 品牌
          spec: undefined, // 规格
          material: undefined, // 材质
          other: undefined, // 其他
          amount: undefined, // 数量
          warehouseName: undefined, // 仓库
          price: undefined, // 价格
          premium: undefined // 升贴水
        }
      ];
    },
    designateCompanyChange(val) {
      if (!val) this.designateCompanyForm.companys = [];
    },
    // 选择品种
    changeCategory(val) {
      this.form.contract = undefined;
      if (val.length !== 0) this.futuresCode = val[val.length - 1].futureCode;
    },
    // 商品信息新增一行
    goodsDataAdd() {
      let row = Object.assign({}, this.form.goodsData[0]);
      this.form.goodsData.push(row);
    },
    // 商品信息删除一行
    goodsDataDel(idx) {
      this.form.goodsData.splice(idx, 1);
    },
    // 检查商品信息
    checkProductInfo() {
      return new Promise(resolve => {
        this.$refs.productInfo.isSameGoods().then(() => {
          this.$refs.productInfo.checkWarehousePremium().then(() => {
            this.$refs.productInfo.checkWarehouse().then(res => {
              resolve(res);
            });
          });
        });
      });
    },
    // 当天之前的日期不可选
    disabledDate(current) {
      return current.format("YYYY-MM-DD") < moment().format("YYYY-MM-DD");
    },
    // 发布前校验
    submitVerify() {
      this.$refs.designateCompany.checkout().then(() => {
        this.$refs.issueForm.validated().then(() => {
          this.checkProductInfo().then(res => {
            // 发布点价要进行历史升贴水对比
            if (this.form.priceType === 1) {
              let params = res;
              params.forEach(item => {
                item.categoryId = this.form.category[
                  this.form.category.length - 1
                ];
              });
              // 历史升贴水对比
              this.historyPremiumVerify(params)
                .then(() => {
                  this.submit(res);
                })
                .catch(err => {
                  let _this = this;
                  if (
                    err.code === this.$globalSite.errorCode.verifyhistorypremium
                  ) {
                    let el = this.dealHistoryPremiumVerifyMsg(err.data);
                    this.$confirm({
                      title: "温馨提示",
                      content: el,
                      onOk() {
                        return new Promise(resolve => {
                          _this.submit(res).then(() => {
                            resolve();
                          });
                        });
                      }
                    });
                  }
                });
            } else {
              this.submit(res);
            }
          });
        });
      });
    },
    // 历史升贴水对比
    historyPremiumVerify(goodsData) {
      return new Promise((resolve, reject) => {
        verifyhistorypremium(goodsData)
          .then(() => {
            resolve();
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    // 发布报价
    submit(goodsData) {
      this.submitLoading = true;
      let params = {
        companyLimit: this.designateCompanyForm.companys.map(i => i.key), // 指定公司
        categoryId: this.form.category[this.form.category.length - 1], // 品种
        futuresContract: this.form.contract, // 合约月
        priceType: this.form.priceType, // 作价方式
        slidePriceType:
          this.form.priceType === quotationDict.priceType.pricing.value
            ? this.form.slidePriceType
            : undefined, //确定价不需传输入价格slidePriceType
        premiumIsshow: this.form.premiumIsshow, // 升贴水显隐
        rateLimit: this.form.multiple, // 下单倍数
        deliveryType: this.form.deliveryType, // 交货方式
        invoiceType: this.form.invoiceType, // 开票日期
        settlementType: this.form.settlementType, // 结算方式
        expirationDate: Number(this.form.cutoffDate), // 截止日期
        remark: this.form.remark, // 备注
        quotationDetails: goodsData, // 商品信息
        lineId: this.form.lineSwitch === 1 ? this.form.line : undefined // 线路
      };
      if (this.isUpdating) params.version = this.updateQuotationDetail.version; // 编辑时需传版本号
      // 编辑和新发布调用不同接口
      let submitFunc;
      if (this.$route.name === "quotationUpdate") {
        submitFunc = updatequotation;
        params.id = this.updateQuotationDetail.id;
      } else {
        submitFunc = releaseQuotation;
      }
      return new Promise(resolve => {
        // 商品信息通过
        submitFunc(params)
          .then(res => {
            let msg =
              res.quotationType === this.quotationDict.status.onsale.value
                ? "发布成功"
                : "报价已发布，等待审核";
            this.$message.success(msg);
            this.$router.push({ name: "quotationList" });
          })
          .finally(() => {
            this.submitLoading = false;
            resolve();
          });
      });
    },
    // 获取报价信息，用于查询最新报价详情
    getQuotationDetail() {
      let params = this.$route.params;
      if (params.quotationDetail) {
        this.$storage.s_set("updateQuotationDetail", params.quotationDetail); // 存储在session，刷新后获取
        this.getQuotationDetailNewest(params.quotationDetail);
      } else {
        if (this.$storage.s_get("updateQuotationDetail")) {
          this.getQuotationDetailNewest(
            this.$storage.s_get("updateQuotationDetail")
          );
        } else {
          this.$error({
            title: "数据错误，请返回报价列表重新进入"
          });
        }
      }
    },
    // 获取最新报价详情
    getQuotationDetailNewest(params) {
      getquotationdetailtoupdate(params).then(res => {
        this.getContractList(res.quotation.categoryId);
        this.updateQuotationId = res.quotation.id;
        this.originalData = res.quotation.quotationDetailList;
        this.quotationBackfill(res.quotation, res.auditQuotation);
      });
    },
    // 编辑时查询对应的合约月
    getContractList(categoryId) {
      let categorys = this.$storage.s_get("category");
      categorys = categorys.filter(i => !i.children);
      for (let i = 0; i < categorys.length; i++) {
        if (categorys[i].id === categoryId) {
          this.futuresCode = categorys[i].futureCode;
        }
      }
    },
    // 回填报价信息
    quotationBackfill(data, auditData) {
      this.updateQuotationDetail = data;
      // 指定公司
      if (data.companyLimitDetail && data.companyLimitDetail.length !== 0) {
        this.$refs.designateCompany.changeSwitch(true);
        let companyLimit = [];
        data.companyLimitDetail.forEach(item => {
          companyLimit.push({
            key: item.id,
            label: item.companyName
          });
        });
        this.designateCompanyForm.companys = companyLimit;
      }
      let goodsData = auditData || data;
      // 编辑报价返回的数量字段是amountTotal，需要替换成amount
      goodsData.quotationDetailList.forEach(item => {
        // 商品信息版本号version要用quotation的
        if (auditData) {
          let idx = findIndex(data.quotationDetailList, ["id", item.id]);
          if (idx !== -1) item.version = data.quotationDetailList[idx].version;
        }
        // 替换对应字段用于回写
        item.amount = item.amountTotal;
        delete item.amountTotal;
      });
      this.form.goodsData = auditData
        ? auditData.quotationDetailList
        : data.quotationDetailList; // 商品信息，有待审核信息的时候商品信息回写待审核的信息
      this.form.priceType = data.priceType;
      this.form.category = [data.categoryId];
      this.form.contract = goodsData.futuresContract; // 合约月
      this.form.deliveryType = goodsData.deliveryType; // 交货方式
      this.form.invoiceType = goodsData.invoiceType; // 开票日期
      this.form.settlementType = goodsData.settlementType; // 结算方式
      this.form.remark = goodsData.remark; // 备注
      this.form.cutoffDate = goodsData.expirationDate.toString(); // 截止日期
      this.form.premiumIsshow = goodsData.premiumIsshow; // 是否显示升贴水
      this.form.rateLimitType = goodsData.rateLimitType; // 开启下单倍数
      if (goodsData.lineId) {
        this.form.lineSwitch = 1;
        this.form.line = goodsData.lineId;
      }
      if (goodsData.rateLimitType === 0)
        this.form.multiple = goodsData.rateLimit; // 下单倍数
      let props = this.formData.map(i => i.prop);
      let changeProps = ["slidePriceType", "contract", "premiumIsshow"];
      changeProps.forEach(item => {
        let idx = props.indexOf(item);
        this.formData[idx].hidden = data.priceType === 1 ? false : true;
      });
    },
    // 设置默认时间
    // 发布报价的截止日期默认选择当天下午三点，如果过了这个时间，默认选择第二天下午三点
    getDefaultTime() {
      let date = getTime();
      this.form.cutoffDate = moment(date).valueOf() + "";
    },
    // 获取线路
    getOrderLines() {
      return new Promise(resolve => {
        getline().then(res => {
          resolve(res);
        });
      });
    }
  },
  created() {
    // 是否在编辑状态
    if (this.$route.name === "quotationUpdate") {
      this.isUpdating = true;
      this.getQuotationDetail();
    } else {
      this.isUpdating = false;
      this.getDefaultTime();
    }
  },
  beforeDestroy() {
    this.$storage.s_remove("updateQuotationDetail");
  }
};
</script>

<style lang="scss" scoped>
.designateCompany {
  .title {
    font-weight: bold;
    font-size: 16px;
  }
  .tip {
    margin-top: 6px;
    color: rgba(0, 0, 0, 0.45);
    font-weight: bolder;
  }
}
::v-deep .form-wrapper {
  .ant-input,
  .ant-input-number,
  .ant-select,
  .ant-cascader-picker {
    width: 200px;
  }
  textarea.ant-input {
    width: 50%;
  }
  .ant-alert {
    width: fit-content;
  }
}
::v-deep .designateCompany .ant-form-item {
  margin-top: 20px;
  margin-bottom: 0;
  .ant-select {
    width: 50%;
  }
}
.cutoffDate {
  .divide {
    margin: 0 15px;
  }
  .time {
    margin-left: 10px;
  }
  .ant-select {
    width: 100px;
  }
}
</style>
